<template>

  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button type="success" plain icon="Edit"  :disabled="!disabledForm" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="primary" plain icon="Upload" @click="handleImport" v-hasPermi="['system:user:import']">导入询价产品</el-button>
    </el-col>

    <right-toolbar :search="false" @queryTable="handleInquiry" ></right-toolbar>
  </el-row>

<!--  <el-card style="margin-bottom: 5px;">-->
    <el-form ref="projectsRef" :model="form" :rules="rules" label-width="92px" :disabled="disabledForm">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="项目编号" prop="projectCode">
            <el-input v-model="form.projectCode" placeholder="请输入项目编号" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker clearable
                            v-model="form.startDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择开始日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker clearable
                            v-model="form.endDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择开始日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
<!--        <el-col :span="5">-->
<!--          <el-form-item label="项目ID" prop="projectId">-->
<!--            <el-input :value="projectId" disabled />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>
      <el-row :gutter="24">


      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="客户简写" prop="customerTitle">
            <el-input v-model="form.customerTitle" placeholder="请在客户全称中选择" readonly disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户全称" prop="customerId">
            <!--              <el-input v-model="form.customerTitle" placeholder="请输入客户名称" />-->
            <el-select
                v-model="form.customerId" filterable remote reserve-keyword placeholder="请输入简称"
                :remote-method="remoteMethodOfCustomer" @change="handleChangeOfCustomer" :loading="loading" >
              <el-option
                  v-for="item in optionsOfCustomer" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="客户联系人" prop="customerContactId">
<!--            <el-input v-model="form.customerContactName" placeholder="请输入客户联系人" />-->
            <el-select
                v-model="form.customerContactId" filterable remote reserve-keyword placeholder="请输入客户联系人"
                :remote-method="remoteMethodOfCustomerContacts" @change="handleChangeOfCustomerContacts" :loading="loading" >
              <el-option label=" - " :value="0" />
              <el-option
                  v-for="item in optionsOfCustomerContacts" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="项目负责人" prop="ownerUserId">
<!--            <el-input v-model="form.ownerUserName" placeholder="请输入项目负责人名称" />-->
            <el-select
                v-model="form.ownerUserId" filterable remote reserve-keyword placeholder="请输入简称"
                :remote-method="remoteMethodOfUser" @change="handleChangeOfUser" :loading="loading" >
              <el-option
                  v-for="item in optionsOfUser" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">

        <el-col :span="6">
          <el-form-item label="项目状态" prop="projectStatus">
            <el-select v-model="form.projectStatus" placeholder="请选择项目状态">
              <el-option
                  v-for="dict in scm_project_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="采购类型" prop="purchaseCategory">
            <el-select v-model="form.purchaseCategory" placeholder="请选择采购类型">
              <el-option
                  v-for="dict in scm_purchase_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部品类型" prop="demandType">
            <el-select v-model="form.demandType" placeholder="请选择部品类型">
              <el-option
                  v-for="dict in scm_demand_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="预算金额" prop="budget">
            <el-input-number v-model="form.budget" placeholder="请输入供应商币种汇率" type="number" :min="0" :controls="false" :precision="2" class="number-right" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="我的币种" prop="myCurrency">
            <el-select v-model="form.myCurrency" placeholder="请选择我的币种">
              <el-option
                v-for="dict in scm_currency"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="客户币种" prop="customerCurrency">
            <el-select v-model="form.customerCurrency" placeholder="请选择客户币种">
              <el-option
                v-for="dict in scm_currency"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="客户币种汇率" prop="customerCurrencyRate" label-width="110">
            <el-input-number v-model="form.customerCurrencyRate" placeholder="请输入客户币种汇率" type="number" :min="0" :controls="false" class="number-right" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="供应商币种" prop="supplierCurrency">
            <el-select v-model="form.supplierCurrency" placeholder="请选择供应商币种">
              <el-option
                v-for="dict in scm_currency"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="供应商币种汇率" prop="supplierCurrencyRate" label-width="110">
            <el-input-number v-model="form.supplierCurrencyRate" placeholder="请输入供应商币种汇率" type="number" :min="0" :controls="false" class="number-right" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="14">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="5" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  <div v-if="!disabledForm" style="display: flex; justify-content: flex-end;">
    <el-button type="primary" @click="submitForm">保 存</el-button>
    <el-button @click="cancel">取 消</el-button>
  </div>

<!--  </el-card>-->

  <import-excel-dialog
      templateFileName="询价数据模板"
      v-model="showImportDialog"
      import-url="/scm/scmImportInquiriesIn/importData"
      template-url="/scm/scmImportInquiriesIn/importTemplate"
      :project-id="localProjectId"
      @success="handleImportSuccess"
  />

</template>

<script setup>
// import { defineProps } from 'vue';
// 确保在文件顶部导入必要的函数
import { ref, reactive, toRefs, getCurrentInstance, watch } from "vue";

import { listProjects, getProjects, delProjects, addProjects, updateProjects } from "@/api/scm/projects";
import ImportExcelDialog from "@/components/ExcelImport/index.vue";
import {listCustomer} from "@/api/scm/customer";
import {listUser} from "@/api/system/user";
import {listCustomerContacts} from "@/api/scm/customerContacts";

const { proxy } = getCurrentInstance();
const { scm_project_status, scm_purchase_category, scm_demand_type, scm_currency } = proxy.useDict('scm_project_status', 'scm_purchase_category', 'scm_demand_type', 'scm_currency');


const props = defineProps({
  projectId: {                  // 新增的 prop
    type: [Number, String],     // 支持数字或字符串类型
    required: false,            // 非必须
    default: null               // 默认值为 null
  }
});
const localProjectId = ref(props.projectId);

// 监听 projectId 变化
watch(
    () => props.projectId,
    (newVal) => {
      console.log('projectId changed to:', newVal);
      localProjectId.value = newVal; // 更新本地变量
      handleInquiry();
    }
);

const disabledForm = ref(true);
const backupForm = reactive({});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectCode: null,
    projectName: null,
    customerTitle: null,
    ownerUserName: null,
    startDate: null,
    endDate: null,
    projectStatus: null,
    purchaseCategory: null,
    demandType: null,
  },
  rules: {
    // projectCode: [
    //   { required: true, message: "项目编号不能为空", trigger: "blur" }
    // ],
    projectName: [
      { required: true, message: "项目名称不能为空", trigger: "blur" }
    ],
    customerTitle: [
      { required: true, message: "客户简写不能为空", trigger: "blur" }
    ],
    // ownerUserId: [
    //   { required: true, message: "项目负责人ID不能为空", trigger: "blur" }
    // ],
    ownerUserName: [
      { required: true, message: "项目负责人名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const loading = ref(false);

// 表单重置
function reset() {
  form.value = {
    projectId: null,
    projectCode: null,
    projectName: null,
    customerId: null,
    customerTitle: null,
    customerContactId: null,
    customerContactName: null,
    ownerUserId: null,
    ownerUserName: null,
    myCurrency: null,
    customerCurrency: null,
    supplierCurrency: null,
    customerCurrencyRate: null,
    supplierCurrencyRate: null,
    startDate: getCurrentDate(),
    endDate: null,
    projectStatus: null,
    purchaseCategory: null,
    demandType: null,
    budget: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("projectsRef");
}

/** 修改按钮操作 */
function handleInquiry() {
  reset();
  const _projectId = localProjectId.value
  if (_projectId == null || _projectId === '' || _projectId === 0 || _projectId === "0" )
    return;
  getProjects(_projectId).then(response => {
    form.value = response.data;
    initializeCustomerOptions(response.data.customerId);
    initializeUserOptions(null);
    initializeCustomerContactsOptions(form.value.customerId)
    // open.value = true;
    // title.value = "修改项目管理";
  });
}

// 取消按钮
function cancel() {
  // form.value = backupForm.value;
  Object.assign(form.value, backupForm);

  disabledForm.value = true;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectsRef"].validate(valid => {
    if (valid) {
      if (form.value.projectId != null) {
        updateProjects(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          disabledForm.value = true;
          handleInquiry();
          // open.value = false;
          // getList();
        });
      } else {
        addProjects(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          disabledForm.value = true;
          handleInquiry();
          // open.value = false;
          // getList();
        });
      }
    }
  });
}

// 获取当前日期函数（格式 YYYY-MM-DD）
function getCurrentDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const showImportDialog = ref(false)
// const single = ref(false);
/** 导入按钮操作 */
function handleImport() {
  // upload.title = "用户导入";
  showImportDialog.value = true;
}
function handleImportSuccess(response) {
  console.log('导入成功:', response)
}

function handleUpdate(){
  // backupForm.value = form.value;
  Object.assign(backupForm, form.value); // 深度复制当前表单状态
  disabledForm.value = false;
}



// 客户下拉框
const optionsOfCustomer = ref([]);
const customerList = ref([]);
const queryParamsOfCustomer = ref({});

function resetQueryOfCustomer() {
  queryParamsOfCustomer.value = {
    pageNum: 1,
    pageSize: 100,
    id: null,
    customerNo: null,
    name: null,
    nickname: null,
  }
}
function remoteMethodOfCustomer(query) {
  console.log('query', query);
  resetQueryOfCustomer();
  if (query !== ''){
    queryParamsOfCustomer.value.nickname = query.trim();
    listCustomerSelect();
  }
}
function initializeCustomerOptions(customerId) {
  console.log('customerId', customerId)
  resetQueryOfCustomer();
  queryParamsOfCustomer.value.id = customerId;
  listCustomerSelect();
  queryParamsOfCustomerContacts.value.customerId = customerId;
  listCustomerContactsSelect();
}
function handleChangeOfCustomer(value) {
  console.log('value', value);
  // form.value.customerId = value;
  form.value.customerTitle = customerList.value.find(customer => customer.id === value).nickname;
  form.value.customerContactId = 0;
  form.value.customerContactName = " ";
  // 根据 value 找到对应的 label
  // const selectedOption = optionsOfCustomer.value.find(option => option.value === value);
  // if (selectedOption) {
  //   form.value.customerTitle = selectedOption.label; // 将 label 赋值给 customerTitle
  // }
  queryParamsOfCustomerContacts.value.customerId = value;
  listCustomerContactsSelect();
}
function listCustomerSelect() {
  listCustomer(queryParamsOfCustomer.value).then(response => {
    customerList.value = response.rows;
    optionsOfCustomer.value = customerList.value.map(customer => ({
      label: customer.name,
      value: customer.id,
    }));
  });
}

//客户联系人下拉菜单
const optionsOfCustomerContacts = ref([]);
const customerContactsList = ref([]);
const queryParamsOfCustomerContacts = ref({});

function resetQueryOfCustomerContacts() {
  queryParamsOfCustomerContacts.value = {
    pageNum: 1,
    pageSize: 100,
    id: null,
    customerId: null,
  }
}
function remoteMethodOfCustomerContacts(query) {
  console.log('query', query);
  resetQueryOfCustomerContacts();
  if (query !== ''){
    queryParamsOfCustomerContacts.value.nickname = query.trim();
    // listCustomerContactsSelect();
  }
}
function initializeCustomerContactsOptions(customerContactsId) {
  console.log('customerContactsId', customerContactsId)
  resetQueryOfCustomerContacts();
  queryParamsOfCustomerContacts.value.id = customerContactsId;
  listCustomerContactsSelect();
}
function handleChangeOfCustomerContacts(value) {
  console.log('value', value);
  // form.value.customerContactsId = value;
  form.value.customerContactName = customerContactsList.value.find(customerContacts => customerContacts.id === value).contactName;
  // 根据 value 找到对应的 label
  // const selectedOption = optionsOfCustomerContacts.value.find(option => option.value === value);
  // if (selectedOption) {
  //   form.value.customerContactsTitle = selectedOption.label; // 将 label 赋值给 customerContactsTitle
  // }
}
function listCustomerContactsSelect() {
  listCustomerContacts(queryParamsOfCustomerContacts.value).then(response => {
    customerContactsList.value = response.rows;
    optionsOfCustomerContacts.value = customerContactsList.value.map(customerContacts => ({
      label: customerContacts.contactName,
      value: customerContacts.id,
    }));
  });
}

//负责人下拉菜单
const optionsOfUser = ref([]);
const userList = ref([]);
const queryParamsOfUser = ref({});

function resetQueryOfUser() {
  queryParamsOfUser.value = {
    pageNum: 1,
    pageSize: 100,
    userName: undefined,
    nickName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  }
}
function remoteMethodOfUser(query) {
  console.log('query', query);
  resetQueryOfUser();
  console.log('userList.value.length', userList.value.length);
  if (userList.value.length === 0){
    queryParamsOfUser.value.nickName = query.trim();
    listUserSelect();
  }
}
function initializeUserOptions(userId) {
  console.log('userId', userId)
  resetQueryOfUser();
  queryParamsOfUser.value.userId = userId;
  listUserSelect();
}
function handleChangeOfUser(value) {
  console.log('value', value);
  // form.value.userId = value;
  form.value.ownerUserName = userList.value.find(user => user.userId === value).nickName;
  // 根据 value 找到对应的 label
  // const selectedOption = optionsOfUser.value.find(option => option.value === value);
  // if (selectedOption) {
  //   form.value.userTitle = selectedOption.label; // 将 label 赋值给 userTitle
  // }
}
function listUserSelect() {
  listUser(queryParamsOfUser.value).then(response => {
    userList.value = response.rows;
    optionsOfUser.value = userList.value.map(user => ({
      label: user.nickName,
      value: user.userId,
    }));
  });
}

//初始化
handleInquiry();



</script>
